import dayjs from 'dayjs'
import { dictStore } from '@/pinia/modules/dict'
import { isUndefined, isNull } from 'lodash-es'


function calComponent(item) {
  const modules = import.meta.glob('@/view/**/*.vue')
  return modules['/src/view' + item.component]
}

export function changeSize(limit) {
  var size = "";
  if (limit < 0.1 * 1024) {                            //小于0.1KB，则转化成B
    size = limit.toFixed(2) + "B"
  } else if (limit < 0.1 * 1024 * 1024) {            //小于0.1MB，则转化成KB
    size = (limit / 1024).toFixed(2) + "KB"
  } else if (limit < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB"
  } else {                                            //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
  }

  var sizeStr = size + "";                        //转成字符串
  var index = sizeStr.indexOf(".");                    //获取小数点处的索引
  var dou = sizeStr.substr(index + 1, 2)            //获取小数点后两位的值
  if (dou == "00") {                                //判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}

export function formatAuthByResource(menu) {
  const authBtn = []
  const getBtnArr = (menu) => {
    menu.forEach(item => {
      if (item.type == '3') {
        if (item.frontendRouting) {
          authBtn.push(item.frontendRouting)
        }
      }
      if (item.children && item.children.length > 0) {
        getBtnArr(item.children)
      }
    })
  }
  getBtnArr(menu)
  return authBtn
}

export function formatRoutesByAPI(menu, val) {
  let level = 1
  const asyncRoutes = []

  menu.forEach(item => {
    if (val) {
      level = val + 1
    }
    if (item.status == 0) {
      // 禁用菜单
      return
    }
    const routerObj = {
      path: (item.type == 0 && item.isFullScreen == '1') ? '/' + item.code : item.code,
      component: calComponent(item),
      name: item.code,
      redirect: item.redirect,
      hidden: item.isDisplayInMainMenu == 0,
      isFullScreen: item.isFullScreen,
      isShowLeftMenus: item.isShowLeftMenus,
      isShowHistoryTag: item.isShowHistoryTag,
      meta: {
        title: item.name,
        type: item.type,
        icon: item.icon,
        id: item.id,
        isFullScreen: item.isFullScreen,
        isShowLeftMenus: item.isShowLeftMenus,
        isShowHistoryTag: item.isShowHistoryTag,
        hidden: item.isDisplayInMainMenu === 0,
        keepAlive: item.keepAlive == 1 ? true : false,
        activeName: item.activeName || '',
        closeTab: item.closeTab == 1 ? true : false
      },
      level,
      children: item.children ? formatRoutesByAPI(item.children, level) : []
    }
    asyncRoutes.push(routerObj)

  })
  return asyncRoutes
}

// 根据身份证号算出 年龄 出生日期 性别
// type:Number类型 1出生日期 2.性别 3.年龄
export function calAgeAndSexByIdCard(idCard, type, text) {
  const regIdCard =
    /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (!idCard || !regIdCard.test(idCard)) {
    return null;
  }
  if (type === 1) {
    // 获取出生日期
    const birth =
      idCard.substring(6, 10) +
      '-' +
      idCard.substring(10, 12) +
      '-' +
      idCard.substring(12, 14)
    return birth
  }
  if (type === 2) {
    // 获取性别
    if (parseInt(idCard.substr(16, 1)) % 2 === 1) {
      // 男
      return text ? '男' : '1'
    } else {
      // 女
      return text ? '女' : '2'
    }
  }
  if (type === 3) {
    const birthYearMonthDay =
      idCard.substring(6, 10) +
      '-' +
      idCard.substring(10, 12) +
      '-' +
      idCard.substring(12, 14)
    const birthDate = new Date(birthYearMonthDay);
    // 获取年龄
    const momentDate = new Date();
    momentDate.setHours(0, 0, 0, 0); //因为new Date()出来的时间是当前的时分秒。我们需要把时分秒重置为0。使后面时间比较更精确
    const thisYearBirthDate = new Date(
      momentDate.getFullYear(),
      birthDate.getMonth(),
      birthDate.getDate()
    );
    const aDate = thisYearBirthDate - birthDate;
    const bDate = momentDate - birthDate;
    let tempAge = momentDate.getFullYear() - birthDate.getFullYear();
    let age = null;
    if (bDate < aDate) {
      tempAge = tempAge - 1;
      age = tempAge < 0 ? 0 : tempAge;
    } else {
      age = tempAge;
    }
    return age;
  }
}

// 身份证号验证f放
export function  validateIdCardMethods(value) {
  const regIdCard =
    /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (regIdCard.test(value)) {
    return true
  } else {
    return false
  }
}
// 根据出生日期计算年龄 传入YYYY-MM-DD
export function getAgeByBirthday(birthDay) {
  if (birthDay) {
    var birthDayNum = birthDay.split('-').join('')
    var myDate = new Date()
    var month = myDate.getMonth() + 1
    var day = myDate.getDate()
    var age = myDate.getFullYear() - birthDayNum.substring(0, 4) - 1
    if (
      birthDayNum.substring(4, 6) < month ||
      (birthDayNum.substring(4, 6) === month && birthDayNum.substring(6, 8) <= day)
    ) {
      age++
    }
    return age
  }
}

// 处理area-cascader返回的数组
// type:处理字段属性名
// arr： area-cascader返回的数组
const AREA_KEY_NAME = {
  1: ['provinceCode', 'cityCode', 'countyCode', 'streetCode', 'communityCode'],
  2: [
    'unitProvinceCode',
    'unitCityCode',
    'unitCountyCode',
    'unitStreetCode',
    'unitCommunityCode'
  ],
  3: [
    'currentProvinceCode',
    'currentCityCode',
    'currentCountyCode',
    'currentStreetCode',
    'currentCommunityCode'
  ],
  4: [
    'registerProvinceCode',
    'registerCityCode',
    'registerCountyCode',
    'registerStreetCode',
    'registerCommunityCode'
  ],
  5: [
    'reservationCurrentProvinceCode',
    'reservationCurrentCityCode',
    'reservationCurrentCountyCode',
    'reservationCurrentStreetCode',
    'reservationCurrentCommunityCode'
  ],
  6: [
    'permanentProvinceCode',
    'permanentCityCode',
    'permanentCountyCode',
    'permanentStreetCode',
    'permanentCommunityCode'
  ]
}
export function renderAreaCode(type, arr, targetObj) {
  // let result = {}
  AREA_KEY_NAME[type].map((item, index) => {
    targetObj[item] = arr[index] ? arr[index] : ''
    // result[item] = arr[index]?arr[index]:''
  })
  // return result
}

// 把接口返回的区划数据 处理为数组
export function renderAreaArr(type, obj) {
  let areaArr = []
  AREA_KEY_NAME[type].map((item, index) => {
    obj[item] && areaArr.push(obj[item])
  })
  return areaArr
}

export function disabledNextDate(date) {
  return dayjs().isBefore(dayjs(date))
}


export const filterDict = (value, options) => {
  const rowLabel = options && options.filter(item => item.value === value)
  return rowLabel && rowLabel[0] && rowLabel[0].label
}

export const formatDictCode = (code, val) => {
  // eslint-disable-next-line eqeqeq
  const target = dictStore().dict?.find(item => item.code == code)
  if (target && (val || val === 0 || val === '0') && val !== '--') {
    // if (Array.isArray(val)) {
    // 如果是数组
    let res = ''
    val
      .toString()
      .split(',')
      .forEach((item, index) => {
        // eslint-disable-next-line eqeqeq
        const a = target.children.find(item1 => item1.code == item)
        if (a) {
          res += `${index === 0 ? '' : ','}${a.name}`
        } else {
          res += ''
        }
        // eslint-disable-next-line eqeqeq
      })
    return res
  }
  return '--'
}

export const formatValue = (item) => {
  if (isUndefined(item.value) || isNull(item.value) || item.value === '') {
    return '--'
  }

  if (item.type === 'dict') {
    const options = dictStore().dict?.filter(
      (item1) => item1.code == item.dictCode
    )[0];
    return options.children.filter((item2) => item2.code == item.value)[0].name;
  }
  if (item.type === 'dictCheckbox') {
    const options = dictStore().dict?.filter(
      (item1) => item1.code == item.dictCode
    )[0];
    let arr = [];
    item.value.split(',').forEach((item2) => {
      arr.push(options.children.filter((item3) => item3.code == item2)[0].name);
    });
    return arr.join(',');
  }
  if (item.type === 'Area') {
    return '行政区划'
  }
  return item.value
}

const FORMAT_ADDRESS_TYPE = {
  1: ['provinceName', 'cityName', 'countyName', 'streetName', 'communityName'],
}
export const formatAddress = (data, type) => {
  if (data) {
    const res = []
    FORMAT_ADDRESS_TYPE[type].forEach(item => {
      if (data[item]) {
        res.push(data[item])
      }
    })
    return res.join('')
  }
  return '--'
}
